package com.ray.test.util;

import com.ray.test.actuator.params.ParamsBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Parameter;
import java.util.List;

/**
 * @author bo shen
 * @Description: 手动实例化对象
 * @Class: ClassInstanceUtil
 * @Package com.ray.test.util
 * @date 2019/12/18 13:30
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class ClassInstanceUtil {

    public static Object getObject(Class<?> classType) {
        Object value = null;
        try {
            Constructor constructor = null;
            //默认构造
            try {
                constructor = classType.getConstructor();
            } catch (Exception e) {
                log.info("{}没有无参构造方法", classType);
            }
            if (constructor != null) {
                value = classType.newInstance();
            } else {
                Constructor[] constructors = classType.getDeclaredConstructors();
                //查询到构造
                if (constructors != null && constructors.length > 0) {
                    for (Constructor constructor1 : constructors) {
                        Parameter[] parameters = constructor1.getParameters();
                        if (parameters.length == 1) {
                            List<Object> params = ParamsBuilder.getInstance().bulider(parameters, null, null);
                            constructor1.setAccessible(true);
                            value = constructor1.newInstance(params.get(0));
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.info("手动实例化{}异常", classType);
        }
        return value;
    }
}
